<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 传给左插槽 -->
        <template #left>
          <span>总记录数:{{ total }} 条</span>
        </template>
        <!-- 传给右插槽 -->
        <template #right>
          <el-button
            v-permission="'excel_import'"
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
          >excel导入</el-button>
          <el-button
            v-if="hasPointsPermission('excel_export')"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-if="hasPointsPermission('p-em-add')"
            type="primary"
            size="small"
            @click="addEmployess"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card
        v-loading="isLoading"
        style="margin-top: 10px;"
      >
        <el-table
          :data="employeeDate"
          border
        >
          <el-table-column
            label="序号"
            align="center"
            type="index"
            :index="indexMethod"
          />
          <el-table-column
            label="姓名"
            prop="username"
            align="center"
          />
          <el-table-column label="头像">
            <template #default="{row}">
              <img
                v-imgErr="nullImage"
                :src="row.staffPhoto || nullImage"
                class="staff"
              >
            </template>
          </el-table-column>

          <el-table-column
            label="手机号"
            prop="mobile"
            align="center"
          />
          <el-table-column
            label="工号"
            prop="workNumber"
            align="center"
          />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            align="center"
            :formatter="formateDate"
          />
          <el-table-column
            label="部门"
            prop="departmentName"
            align="center"
          />
          <el-table-column
            #default="{row}"
            label="入职时间"
            prop="timeOfEntry"
            align="center"
          >
            {{ formateTime(row.timeOfEntry) }}
          </el-table-column>
          <el-table-column
            #default="{row}"
            label="操作"
            fixed="right"
            width="280"
            align="center"
          >
            <template>
              <el-button
                v-if="hasPointsPermission('p-em-look')"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button
                v-if="hasPointsPermission('assign_role')"
                type="text"
                size="small"
                @click="handleRoleDialog(row.id)"
              >分配角色</el-button>
              <el-button
                v-if="hasPointsPermission('emp_delete')"
                type="text"
                size="small"
                @click="delEmployeeDate(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="total,sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10,20,30,40]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
      <addEmployess :show-dialog.sync="showDialog" />
    </div>
    <assignRole
      ref="assignRole"
      :show-role-dialog.sync="showRoleDialog"
      :user-id="userId"
    />
  </div>
</template>

<script>
import addEmployess from './components/addEmployess.vue'
import { getEmployeeDateApi, delEmployeeDateApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
import assignRole from '@/views/employees/components/assign-role.vue'
import permission from '@/mixins/permission'

export default {
  name: 'Employess',
  components: {
    addEmployess,
    assignRole
  },
  mixins: [permission],
  data() {
    return {
      // 员工列表
      employeeDate: [],
      // 分页
      page: 1,
      // 每页几个
      pageSize: 10,
      // 总数据
      total: 0,
      isLoading: false,
      showDialog: false,
      // defaultImg: avatar,
      nullImage:
        'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401',
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeDate()
  },
  methods: {
    // 点击分配权限打开窗口
    handleRoleDialog(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // 时间转换
    formateTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 部门转换
    formateDate(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // 封装获取员工数据函数
    async getEmployeeDate() {
      this.isLoading = true
      const { data: res } = await getEmployeeDateApi(this.page, this.pageSize)
      this.employeeDate = res.data.rows
      this.total = res.data.total
      this.isLoading = false
    },
    // 计算序号
    indexMethod(index) {
      return (this.page - 1) * this.pageSize + index + 1
    },
    // 换页函数
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeDate(this.page, this.pageSize)
    },
    // 页容量改变
    handleSizeChange(val) {
      this.pageSize = val
      this.getEmployeeDate(this.page, this.pageSize)
    },
    // 删除员工
    async delEmployeeDate(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delEmployeeDateApi(id)
          if (this.employeeDate.length === 1 && this.page > 1) {
            this.page--
          }
          // 重新刷新页面
          this.getEmployeeDate(this.page, this.pageSize)
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.error('已取消删除')
        })
    },
    // 点击添加显示弹窗
    addEmployess() {
      this.showDialog = true
    },
    // 跳转到新加员工页
    addEmployessPage() {
      this.page = Math.ceil((this.total + 1) / this.pageSize)
      this.getEmployeeDate()
    },
    // 导出excel
    async exportExcel() {
      // 多表头(复杂表头部分)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并单元格
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 定义表头数组
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      // 连续的解构
      const {
        data: {
          data: { rows } // 结构出来的是一个一维数组,需要转成二维
        }
      } = await getEmployeeDateApi(1, this.total) // 获取员工数据(这样写不规范,需要后端单独给出返回所有数据的接口)
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const data = this.convertTwoDimensionArray(
        headersArr,
        rows,
        headersRelations
      )
      console.log(data)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // excel表头
          data: data, // excel数据(必须是二维数组)
          filename: '员工数据', // 导出文件的文件名
          autoWidth: true, // 单元格宽度是否自适应
          bookType: 'xlsx', // 文件名后缀
          multiHeader,
          merges
        })
      })
    },
    // 转换二维数组
    convertTwoDimensionArray(headersArr, rows, headersRelations) {
      const arr = []
      rows.forEach(item => {
        const tempArray = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          // 转换聘用形式
          if (englishKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(
              item => item.id === Number(value)
            )
            value = obj ? obj.value : '未知'
          }
          // 转换入职日期和转正日期
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? this.formateTime(value) : ''
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    }
  }
}
</script>

<style>
.el-pagination {
  display: flex;
  justify-content: space-between;
}
.staff {
  width: 70px;
  height: 70px;
  border-radius: 50%;
}
</style>
